#pragma once
#include <vector>
#include <iostream>
#include <string>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include "Log.hpp"
#include"mutex.hpp"
using namespace MutexModule;
using namespace LogModule;
class Route
{
private:
    bool ExitUser(InetAddr &peer)
    {
        for (auto &user : _online_user)
        {
            if (user == peer)
            {
                return true;
            }
        }
        return false;
    };
    void AddUser(InetAddr &peer)
    {
        LOG(LogLevel::INFO) << "新增一个用户" << peer.StringAddr();
        _online_user.push_back(peer);
    };

    void DeleteUser(InetAddr &peer)
    {
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == peer)
            {
                _online_user.erase(iter);
                LOG(LogLevel::INFO) << "删除一个用户" << peer.StringAddr() << "成功";
            }
        }
    }

public:
    Route() {};
    void MessageRout(int sockid, std::string message, InetAddr &peer)
    {
        LockGuard lockguard(_mutex);
        if (!ExitUser(peer))
        {
            AddUser(peer);
        }

        std::string send_message = peer.StringAddr() + "# " + message;
        for (auto &user : _online_user)
        {
            int n = sendto(sockid, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&user.NetAddr(), user.Len());
        }
        if (message == "QUIT")
        {
            DeleteUser(peer);
        }
    }

    ~Route() {};

private:
    std::vector<InetAddr> _online_user;
    Mutex _mutex;
};